<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Application_Plugin_Acl
 *
 * @author Eugene
 */
class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{

	/**
	 * @var Core_Acl
	 */
	protected $_acl;

	/**
	 *
	 * @return Core_Acl
	 */
	public function getAcl()
	{
		if (null === $this->_acl) {
			$this->_acl = new Core_Acl;
		}

		return $this->_acl;
	}

	/**
	 *
	 * @param Zend_Controller_Request_Abstract $request
	 * @return void
	 */
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
	{
		$auth = Zend_Auth::getInstance();
		$role = Application_Model_User::ROLE_GUEST;

		if ($auth->hasIdentity()) {
			$role = $auth->getIdentity()->role;
		}

		$resource = $request->module.':'.$request->controller;
		$privilege = $request->action;

		if ($this->getAcl()->has($resource)) {
			if (!$this->getAcl()->isAllowed($role, $resource, $privilege)) {
				$request->setControllerName('index')
						->setActionName('login');
			}
		}
	}

}